package com.itheima.controller;

import com.itheima.common.Code;
import com.itheima.common.MessageConstant;
import com.itheima.common.Result;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @param : 购物车模块-controller层
 * @description:
 * @author: Acer
 * @date: 2022/6/7
 * @return:
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 功能描述:获取购车车内列表数据展示
     *
     * @return
     */
    @GetMapping("/list")
    public Result shoppingList() {
        //1.调用service层定义的方法，返回业务吃力的shoppingcarList结果集合
        List<ShoppingCart> list = shoppingCartService.shoppingList();
        //结果数据封装起来
        if (list == null) {
            //如果集合为空，则新建集合数据
            list = new ArrayList<>();
        }
        return new Result(Code.OK, MessageConstant.CART_GET_SUCCESS, list);

    }

    /**
     * 功能描述:商品添加购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public Result shoppingAdd(@RequestBody ShoppingCart shoppingCart) {
        //调用service方法，获取结果
        ShoppingCart add = shoppingCartService.shoppingAdd(shoppingCart);
        //如果add为空则返回失败提醒
        if (add == null) {
            return new Result(Code.ERROR, MessageConstant.CART_ADD_ERROR);
        }
        System.out.println(add.getNumber());
        return new Result(Code.OK, MessageConstant.CART_ADD_SUCCESS, add);
    }

    /**
     * 1
     * 删除购物车商品
     *
     * @param shoppingCart
     * @return
     */

    @PostMapping("/sub")
    public Result shoppingDel(@RequestBody ShoppingCart shoppingCart) {
        ShoppingCart del = shoppingCartService.shoppingDel(shoppingCart);
        if (del == null) {
            return new Result(Code.ERROR, MessageConstant.CART_DEFAULT_ERROR);
        }
        return new Result(Code.OK, MessageConstant.CART_DEFAULT_SUCCESS, del);
    }

    /**
     * 功能描述 :清空购物车
     *
     * @return
     */
    @DeleteMapping("/clean")
    public Result shoppingDelAll() {
        int row = shoppingCartService.shoppingDelAll();
        if (row < 1) {
            return new Result(Code.ERROR, MessageConstant.CART_CLEAN_ERROR);
        }
        return new Result(Code.OK, MessageConstant.CART_CLEAN_SUCCESS);
    }
}
